package com.gyt.framework.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.gyt.framework.exception.BaseException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.util.StringUtils;

/**
 * @Author created by v_yantgao
 * @Date 2021/1/6 16:37
 */
//@JsonInclude(value = JsonInclude.Include.NON_NULL)
@Data
@ApiModel(description = "响应描述")
public class Response<T> {
    public final static String CODE_OK = "200";
    public final static String MSG_OK = "ok";
    public final static String CODE_ERROR = "500";
    public final static String MSG_ERROR = "error";

    @ApiModelProperty("返回码，200为成功，其他为失败")
    private String code;
    @ApiModelProperty("返回码描述")
    private String msg;
    @ApiModelProperty("结果签名")
    private String sign;
    @ApiModelProperty("详细数据")
    private T data;

    public Response() {
        this.code = CODE_OK;
        this.msg = MSG_OK;
    }

    public Response(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> Response<T> ok(T data){
        Response<T> response = new Response<>();
        response.setData(data);
        return response;
    }
    public static <T> Response<T> ok(T data, String sign){
        Response<T> response = new Response<>();
        response.setData(data);
        response.setSign(sign);
        return response;
    }

    public static <T> Response<T> error(BaseException exception, T data){
        return error(exception.getCode(), exception.getMsg(), data);
    }

    /**
     * 失败结果
     * @param code
     * @param msg
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> error(String code, String msg, T data) {
        Response<T> response = new Response<>(code, msg);
        response.setData(data);
        return response;
    }

    /**
     * 失败结果
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> error(T data) {
        Response<T> response = new Response<>();
        response.setData(data);
        return error(CODE_ERROR, MSG_ERROR, data);
    }

    /**
     * 失败结果
     * @param exception
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> error(Exception exception, T data) {
        return errorException(exception, data);
    }

    /**
     * 失败结果
     * @param exception
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> errorException(Exception exception, T data) {
        String message = exception.getMessage();
        message = StringUtils.isEmpty(message) ? exception.getCause().getMessage() : message;
        Response<T> response = new Response<>();
        response.setCode(CODE_ERROR);
        response.setData(data);
        response.setMsg(message);
        return response;
    }
}